<?php

namespace CtyunOss\cors;

class ArrayObject
{
    public function __construct(array $data = [])
    {
        if (!empty($data)) {
            $properties = $this->getProperties(true);
            foreach (array_keys($properties) as $key) {
                foreach ($data as $k => $v) {
                    if ($k === $key) {
                        $this->{$k} = $v;
                    }
                }
            }
        }
    }

    /**
     * 输出 json 串
     * @return false|string
     * @throws \ReflectionException
     */
    public function toJson()
    {
        return json_encode($this->toArray());
    }

    /**
     * 序列化对象
     * @return string
     */
    public function serialize()
    {
        return serialize($this);
    }

    /**
     * 解序列化对象
     *
     * @param $serialize
     *
     * @return mixed
     */
    public function unserialize($serialize)
    {
        return unserialize($serialize);
    }

    /**
     * 输出数组
     * @return array
     * @throws \ReflectionException
     */
    public function toArray()
    {
        return $this->getProperties(true, true);
    }

    /**
     * 手动字符串化，使用json
     * @return false|string
     */
    public function toString()
    {
        return $this->toJson();
    }

    /**
     * 系统级字符串化
     * @return false|string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * 反射对象属性
     *
     * @param bool $private
     * @param bool $protected
     *
     * @return array
     * @throws \ReflectionException
     */
    protected function getProperties($private = false, $protected = false)
    {
        $class      = new \ReflectionClass($this);
        $properties = $class->getProperties();

        $arr = [];
        foreach ($properties as $property) {
            if ($private && $property->isPrivate()) continue;
            if ($protected && $property->isProtected()) continue;

            $property->setAccessible(true);
            $arr[$property->name] = $property->getValue($this);
        }

        return $arr;
    }
}